/**
 * main module
 * 
 * @author strlst <e11907086@student.tuwien.ac.at>
 * @date 2020-12-01
 * @brief contains necessary implementations of methods defined in the main header
 */

#include "main.h"
#include "cpair.h"

void usage() {
    fprintf(stderr, "usage: cpair\n");
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
    char *line;

    /* leave room for null terminated byte */
    line = malloc(BUF_SIZE + 1);
    /* check if line was allocated */
    if (line == NULL)
        die("%s: could not initialize line buffer: %s\n", argv[0], EXIT_FAILURE);

    /* create points buffer */
    point *p;
    size_t points = POINTS, n = 0;
    p = malloc(points * sizeof(point));
    /* check if points were allocated */
    if (p == NULL)
        die("%s: could not allocate points buffer: %s\n", argv[0], EXIT_FAILURE);

    while (fgets(line, BUF_SIZE + 1, stdin) != NULL) {
        /* if all preallocated points are already filled up */
        if (n >= points) {
            /* double points buffer size */
            points *= 2;

            p = realloc(p, points * sizeof(point));

            /* check if points were reallocated */
            if (p == NULL)
                die("%s: could not reallocate points buffer: %s\n", argv[0], EXIT_FAILURE);
        }

        /* parse points */
        if (sscanf(line, "%le %le", &(p[n].x), &(p[n].y)) < 2)
            usage();

        /* count points */
        ++n;
    }

    /* if the array consists of only 1 point, exit without generating output */
    if (n <= 1) {
        /* do nothing */
    } else if (n == 2) {
        /* print base case */
        for (int i = 0; i < n; i++)
            printf("%le %le\n", p[i].x, p[i].y);
    /* if n > 2 */
    } else {
        find_closest_pair(argv, line, p, n);
    }

    /* free resources */
    free(p);
    free(line);

    return EXIT_SUCCESS;
}
